package com.wandian.texas.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.PropertyConfigurator;

import com.wandian.executor.TimerCommand;
import com.wandian.executor.TimerMgr;
import com.wandian.executor.TimerPool;
import com.wandian.texas.BaseCommandObject;
import com.wandian.texas.CalculateCard;
import com.wandian.texas.GameData;
import com.wandian.texas.TestGamePool;
import com.wandian.texas.RoomMgr;
import com.wandian.texas.SessionMgrImp;
import com.wandian.texas.ThreadPool;
import com.wandian.texas.dao.TestDao;
import com.wandian.texas.dao.Impl.TestDaoImpl;
import com.wandian.texas.db.CommonDaoManager;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.db.DaoManager;
import com.wandian.texas.entity.GameRoomEntity;
import com.wandian.texas.entity.LastAction;
import com.wandian.texas.entity.PokerColor;
import com.wandian.texas.entity.UserGameEntity;
import com.wandian.texas.entity.UserInfoEntity;
import com.wandian.texas.entity.WinCardEntity;
import com.wandian.texas.SessionObject;
import com.wandian.util.Config;
import com.wandian.util.DateUtil;
import com.wandian.util.Log;
import com.wandian.util.PathUtil;
import com.wandian.util.RandomUtil;
import com.wandian.xml.RoomConfigItem;

/*
 * @author long
 * @date 2012-10-7 下午10:06:38
 * @qq 108232706
 * @description Test
 */
public class Test {
	// private static String configPath;// =
	// "E:/work/gameserver/target/config/config.properties";

	public static void main(String[] args) {
//		System.out.println(DESUtil.encrypt("root"));
//		System.out.println(DESUtil.encrypt("long"));
//		System.out.println(DESUtil.encrypt("1234"));
		// testWorldMgr();
		// System.out.println(DESUtil.encrypt("sa"));
		// System.out.println(DESUtil.encrypt("1234"));

		// testExecutor();
		// testReentrantLock();
		// testScheduledExecutorService();
		// testRandom();
		// try {
		// commandConsole();
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }

		// testThreadPool();
		// testPriorityBlockingQueue();
		// System.out.println(PathUtil.getAasolutePath(args[0]));
		// System.out.println(PathUtil.getAasolutePath("target/config/log4j.properties"));
		// System.out.println(PathUtil.getAasolutePath("E:/target/config/log4j.properties"));
		// System.out.println(PathUtil.getAasolutePath("/target/config/log4j.properties"));

		// configPath = String.format("%s/%s", System.getProperty("user.dir"),
		// args[0]).replace('\\', '/');
		// System.out.println(String.format("%s,%s",System.getProperty("user.dir"),Test.class.getResource("")));
		// System.out.println(configPath);
		// testInBonus();
		GameData.CONFIGPATH = PathUtil.getAasolutePath(args[0]);// String.format("%s/%s",
		if (!Config.initConfig(GameData.CONFIGPATH)) {
			System.out.println("系统配置文件加载错误，程序退出!");
			return;
		} else {
			PropertyConfigurator.configure(PathUtil.getAasolutePath(Config.getValue("log4j.path")));
			Log.debug("加载配置文件成功");
		}
		testConnection();
		// if (!initComponent(Config.initConfig(GameData.CONFIGPATH), "加载配置文件"))
		// {
		// return;
		// }

		// try {
		// testDb();
		// } catch (Throwable e1) {
		// e1.printStackTrace();
		// }
		// testRoomcode();

		// if (!NetConfig.init()) {
		// Log.error("加载房间xml错误");
		// return;
		// }

		// printRoomtypeMap();
		// testAutoAdd();
		// testSqlserver();
		// testDaemon();
		// testGetTime();
		// testIoBuffer();
		// testSort();
//		testCardType();
		// testWinner();
		/*try {
			for (int i = 0; i < args.length + 1; i++) {
				System.out.println(args[i]);
			}

		} catch (Exception e) {
			StringBuilder sb = new StringBuilder();
			StackTraceElement[] trace = e.getStackTrace();
			for (int i = 0; i < trace.length; i++) {
				sb.append(" at " + trace[i]);
			}
			System.out.println(sb);
			e.printStackTrace();
		}*/
		//		System.out.println(DESUtil.encrypt("scr888"));
		/*int begin = 4;
		int robots = 200;
		int beginRoomId=0;
		int roomcount = 10;
		int roomid;
		for (int i = begin; i < robots+begin; i++) {
			if(i-begin+1>(roomcount-beginRoomId+1)*9)
				roomid=(i-begin)%roomcount+1;//分散在房间
			else{
				roomid=(i-begin)/9+beginRoomId;//装满房间
			}
			System.out.println(i + " roomid "+roomid);
		}*/
//		System.out.println(DateUtil.format(new Date(),DateUtil.DATE_FORMAT));
//		System.out.println(DateUtil.format(new Date(),DateUtil.DATE_FORMAT));
//		testPokers();
//		testWinner();
//		testCardType1();
//		int[] listObj = new int[] { 2, 8, 8, 9, 1, 0, 3, 0, 0, 0 };
//		CalculateCard.sortAsc(listObj, 7);
//		CalculateCard.remove(listObj, 7, 2);
//		CalculateCard.add(listObj, 6, 3);
//		System.out.println("exit");
//		testInBonusPool();
	}

	private static void testInBonusPool() {
		GameRoomEntity game = new GameRoomEntity();
		int[] seatChip = new int[] { 17433, 17433, 4900, 0, 100, 0, 0, 5000 };
		UserGameEntity user;
		for (int i = 0; i < seatChip.length; i++) {
			game.gameOverSeats[game.gameOverLen++] = i + 1;
			user = game.gameOverUsers[i];
			user.seatChip = seatChip[i];
			user.totalBet = seatChip[i];
			user.user = new UserInfoEntity();
		}
		game.gameOverUsers[3 - 1].lastAction = LastAction.ALLIN;
		game.gameOverUsers[8 - 1].lastAction = LastAction.ALLIN;
		game.InBonusPool();
	}

	private static void testOperate() {
		GameRoomEntity game = new GameRoomEntity();
		game.shuffle();
		String temp = "";
		for (int i = 0; i < game.publicAndSeatPokerIndex.length; i++) {
			temp += game.publicAndSeatPokerIndex[i] + ",";
		}
		System.out.println(temp);
		game.setPublicCard();
		temp = "";
		for (int i = 0; i < 5; i++) {
			temp += game.PublicCard[i] + ",";
		}
		System.out.println(temp);
		com.wandian.util.ArrayList<UserInfoEntity> gameUsers = game.gameUsers;
		UserInfoEntity user;
		UserGameEntity gameuser;
		for (int i = 1; i <= game.gameOverUsers.length; i++) {
			user = new UserInfoEntity();
			user.nickName = String.valueOf(i);
			user.userId = i;
			gameuser = game.gameOverUsers[i - 1];
			game.gameOverUsers[i - 1].cards[0] = game.getSeatPoker(i, 1);
			game.gameOverUsers[i - 1].cards[1] = game.getSeatPoker(i, 2);
			game.gameOverUsers[i - 1].seatId = i;
			gameuser.user = user;
			gameUsers.add(user);
//			game.gameOverUsers[i - 1].bonusIndex = 8;
			game.gameOverUsers[i - 1].calculateCard();
			System.out.println(i + "座位手" + game.gameOverUsers[i - 1].cards[0] + game.gameOverUsers[i - 1].cards[1] + " maxcard:" + game.gameOverUsers[i - 1].getMaxHandcard());
		}
		System.out.println("=======Game Start======");
		while (true) {
			user = game.getNextUser();
			CMD_OPERATION_NEXT(user);
			CMD_OPERATION_REQUEST(user);
			break;
		}
		for (int i = 0; i < game.winnerMap.length; i++) {
			for (int j = 0; j < game.gameOverUsers.length; j++) {
				gameuser = game.gameOverUsers[j];
				if (gameuser.bonusIndex >= i) {
					game.winnerMap[i][game.winnerMapLen[i]++] = gameuser;
				}
			}
			break;
		}
		//计算每边池赢家
		CalculateCard.calculateWinMap(game, 0);
		temp = "";
		for (int i = 0; i < game.winnerMapLen[0]; i++) {
			gameuser = game.winnerMap[0][i];
			temp += gameuser.seatId + ":" + gameuser.getMaxHandcard() + ",";
		}
		System.out.println(temp);
	}

	private static void CMD_OPERATION_REQUEST(UserInfoEntity user) {

	}

	private static void CMD_OPERATION_NEXT(UserInfoEntity user) {
		// TODO Auto-generated method stub

	}

	private static void testWinner() {
//		UserGameEntity[][] winnerMap = new UserGameEntity[9][9];
//	 byte[] winnerMapLen = new byte[9];
//	 UserGameEntity[] gameOverUsers = new UserGameEntity[9];
		GameRoomEntity game = new GameRoomEntity();
//		game.shuffle();
		String[] idx = "47, 9, 43, 46, 36, 18, 17, 7, 13, 19, 8, 32, 14, 28, 4, 42, 51, 24, 40, 5, 29, 41, 38".split(",");
		for (int i = 0; i < idx.length; i++) {
			game.publicAndSeatPokerIndex[i] = Integer.parseInt(idx[i].trim());
		}
		String temp = "";
		for (int i = 0; i < game.publicAndSeatPokerIndex.length; i++) {
			temp += game.publicAndSeatPokerIndex[i] + ",";
		}
		System.out.println(temp);
		game.setPublicCard();
		temp = "";
		for (int i = 0; i < 5; i++) {
			temp += game.PublicCard[i] + ",";
		}
		System.out.println(temp);
//		String[] usernames = new String[] { "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", "test12" };
//		int[] userIds = new int[] { 20, 21, 53, 110, 111, 22, 109, 112, 114 };
//		int[] Idxs = new int[] { 4, 5, 6, 7, 8, 9, 10, 11, 12 };
		boolean[] hasUser = new boolean[9];
		hasUser[0] = true;
		hasUser[1] = true;
		hasUser[2] = true;
		int[] seatIds = new int[] { 2, 5, 0, 0 };
		UserGameEntity user;
		for (int i = 0; i < seatIds.length; i++) {
			if (seatIds[i] < 1)
				break;
			user = game.gameOverUsers[seatIds[i] - 1];
			user.bonusIndex = 0;
			user.cards[0] = game.getSeatPoker(user.seatId, 1);
			user.cards[1] = game.getSeatPoker(user.seatId, 2);
			user.calculateCard();
			game.winnerMap[0][game.winnerMapLen[0]++] = user;
			System.out.println(user.seatId + ":" + user.getMaxHandcard());
		}
		/*for (int i = 1; i <= game.gameOverUsers.length; i++) {
			game.gameOverUsers[i - 1].cards[0] = game.getSeatPoker(i, 1);
			game.gameOverUsers[i - 1].cards[1] = game.getSeatPoker(i, 2);
			game.gameOverUsers[i - 1].seatId = i;
			game.gameOverUsers[i - 1].bonusIndex = 8;
			game.gameOverUsers[i - 1].calculateCard();
			System.out.println(i + "座位手" + game.gameOverUsers[i - 1].cards[0] + game.gameOverUsers[i - 1].cards[1] + " maxcard:" + game.gameOverUsers[i - 1].getMaxHandcard());
		}
		UserGameEntity gameuser;
		for (int i = 0; i < game.winnerMap.length; i++) {
			for (int j = 0; j < game.gameOverUsers.length; j++) {
				gameuser = game.gameOverUsers[j];
				if (gameuser.bonusIndex >= i) {
					game.winnerMap[i][game.winnerMapLen[i]++] = gameuser;
				}
			}
			break;
		}*/
		//计算每边池赢家
		CalculateCard.calculateWinMap(game, 0);
		temp = "=============Winner";
		for (int i = 0; i < game.winnerMapLen[0]; i++) {
			user = game.winnerMap[0][i];
			temp += user.seatId + ":" + user.getMaxHandcard() + ",";
		}
		System.out.println(temp);

	}

	/*private static void testWinner0() {
		GameRoomEntity game = new GameRoomEntity();
	//		game.
		game.PublicCard="Tc,4s,Ah,3d,6c".split(",");
		UserGameEntity gameuser;
		for (int i = 1; i <= game.gameOverUsers.length; i++) {
			gameuser=game.gameOverUsers[i];
			gameuser.seatId=i;
			gameuser.cards[0]="5h";
			gameuser.cards[1]="6s";
			gameuser.calculateCard();
		}
	}*/
	static BaseCommandObject command;
	static ArrayList<SessionObject> sessions = new ArrayList<SessionObject>();

	public static void outRobot() {
		for (int i = 0; i < sessions.size(); i++) {
			RoomMgr.outGame(sessions.get(i), -1, command);
		}
		sessions.clear();
		GameRoomEntity game = RoomMgr.getRoom(1).gameRoom;
		UserGameEntity user;
		for (int i = 0; i < 9; i++) {
			user = game.gameOverUsers[i];
			user.totalBet = 0;
			user.seatChip = 0;
			user.bonusIndex = 0;
		}
	}

	public static void testRobot() {
		String[] usernames = new String[] { "test4", "test5", "test6", "test7", "test8", "test9", "test10", "test11", "test12" };
		int[] userIds = new int[] { 20, 21, 53, 110, 111, 22, 109, 112, 114 };
		int[] Idxs = new int[] { 4, 5, 6, 7, 8, 9, 10, 11, 12 };
		float[] stakes = new float[] { 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000, 5000 };
		SessionObject session;
		UserInfoEntity user;
		command = new BaseCommandObject();
		command.dbIndex = 1;
		if (TestGamePool.isHistory) {
			DaoManager.GameRoomDao(0).getGameBaseInfo(TestGamePool.GameId);
			for (int i = 0; i < TestGamePool.seatIdx.length; i++) {
				if (TestGamePool.seatIdx[i] == 0)
					continue;
				session = new SessionObject(SessionMgrImp.getInstance());
				sessions.add(session);
				user = new UserInfoEntity();
				user.userName = usernames[i];
				user.nickName = usernames[i];
				user.userId = userIds[i];
				user.AccountId = Idxs[i];
				session.setUser(user);
				RoomMgr.inGame(session, 1);
				RoomMgr.sitdownGame(session, 1, (i + 1), 5000, command.dbIndex, command);
			}
			steps = DaoManager.GameRoomDao(0).getGameStep(TestGamePool.GameId);
		} else {
			for (int i = 0; i < 9; i++) {
				if (TestGamePool.seatIdx[i] == 0)
					continue;
				session = new SessionObject(SessionMgrImp.getInstance());
				user = new UserInfoEntity();
				user.userName = usernames[i];
				user.nickName = usernames[i];
				user.userId = userIds[i];
				user.AccountId = Idxs[i];
				session.setUser(user);
				RoomMgr.inGame(session, 1);
				RoomMgr.sitdownGame(session, 1, (i + 1), 5000, command.dbIndex, command);
			}
		}
		boolean isStartGame = true;
//		boolean isNext = true;
		RoomConfigItem room = RoomMgr.getRoom(1);
		isStartGame = TestGamePool.broadcastStartGame(command, 1);
		if (isStartGame) {
			Log.info("=========新游戏开始成功=============gameid:" + room.gameId());
			if (TestGamePool.operationNext(room, command)) {
				Log.info("=========操作下一个成功=============当前坐位:" + room.curSeatId() + " RoundNum:" + room.SNAPCARDS().value());
				Test.doOperationNext(room, command);
			}
//				doOperationNext(room, command);
//				Test.doOperationNext(room, command);
//				TestGamePool.CMD_OPERATION_REQUEST(false, 1, command, null);
		} else {
			Log.info("=========新游戏开始失败=============");
		}
//			isStartGame = false;
		System.out.println("=======Over=======");
	}

	public static class StepEntity {
		public int gameId;
		public int step;
		public int userid;
		public int seatId;
		public int actionType;
		public float giveChip;
		public float seatChip;
		public float stake;
	}

	public static String[] ActionName = new String[] { "Wait", " 看牌", " 弃牌", " 跟注", " 加注", " 全押" };

	static ArrayList<StepEntity> steps = null;

	static int[] actions = new int[] { 3, 1, 5, 5 };
	static float[] giveChip = new float[] { 0, 0, 0, 0 };
	static boolean isArrStep = false;

	public static void doOperationNext(RoomConfigItem room, BaseCommandObject command) {
		UserInfoEntity user = room.getUser(room.curSeatId());
		if (TestGamePool.isHistory) {
			command.sessionObject = room.seatUsers(room.curSeatId());
			int setp = room.step();
			StepEntity step = steps.get(setp - 1);
//			step.gameId = 1;
			action = step.actionType;
			chip = step.giveChip;
			user.stake = step.giveChip + step.stake;

			command.writeBegin();
			command.writeInt(setp);
			command.writeInt(action);
			command.writeFloat(chip);
			command.writeEnd();
			Log.info(setp + ">>>========机器人协助操作下一个成功=============当前坐位:" + room.curSeatId() + " user:" + user.nickName + " action:" + ActionName[action] + action + " chip:" + chip + seatState(room));
			TestGamePool.CMD_OPERATION_REQUEST(false, 1, command, null);
			return;
		}
//		int gameSeatId = room.curSeatId(); // 当前坐位id
		float minCall = room.minCall(); // 桌面最小叫多少
		float maxRaise = room.maxRaise(); // 最小大加注多少
		float minRaise = room.minRaise(); // 最小加注多少
//		float stake = room.stake(); // 玩家的筹码
		if (isArrStep) {
			action = actions[room.step() - 1];
			if (action == 4) {
				chip = giveChip[room.step() - 1];
			}
		} else {
			// PlayerVo playerVo=this.getSitPlayerBySeatId(seatId);
			//		Log.debug(this.curPlayer.name + "----------->>最小叫:" + minCall + " 最大叫:" + maxRaise + " 最小加注:" + minRaise + " 筹码:" + stake + " 先前下注:" + this.curPlayer.callChip + " 最大筹码:" + this._objRoom.maxStake);
			boolean canLook = false;
			boolean canRaise = false;
			boolean canAllin = false;
			boolean canCall = false;
			// 看牌，加注，放弃
			if (minCall == 0) {
				canLook = true;
				canCall = false;
			} else {
				canLook = false;
				canCall = true;
			}
			// 加注，放弃
			// else{
			//
			// }
			if (user.stake + room.callChip(room.curSeatId()) < minCall) {
				canRaise = false;
				canCall = false;
			}
			if (user.stake + room.callChip(room.curSeatId()) > minRaise) {
				if (maxRaise != minRaise) {
					canRaise = true;
				}

			} else {
				canRaise = false;
			}
			if (maxRaise == minRaise) {
				if (user.stake + room.callChip(room.curSeatId()) <= maxRaise) {
					canAllin = true;
				} else {
					canAllin = false;
				}
				canRaise = false;
			}
			// /** * 看牌 */ CHECK(1),///** * 弃牌 */FOLD(2),///** * 跟注 */CALL(3), // /
			// *加注 */RAISE(4),///** * 全押 */ ALLIN(5);//
			ArrayList<Integer> lastAction = new ArrayList<Integer>();
			lastAction.add(2);
			if (canLook) {
				lastAction.add(1);
			}
			if (canCall) {
				lastAction.add(3);
			}
			if (canRaise) {
				lastAction.add(4);
			}
			if (canAllin) {
				lastAction.add(5);
			}
			action = lastAction.get(RandomUtil.next(lastAction.size()));
//			float chip = 0;
			if (action == 4) {
				chip = Math.round(RandomUtil.next(minRaise, maxRaise));
			}
		}
		command.sessionObject = room.seatUsers(room.curSeatId());
//		user=room.getUser(room.curSeatId());
		command.writeBegin();
		command.writeInt(action);
		command.writeFloat(chip);
		command.writeEnd();
		Log.info("========机器人协助操作下一个成功=============当前坐位:" + room.curSeatId() + " user:" + user.nickName + " action:" + ActionName[action] + action + " chip:" + chip + seatState(room));
		TestGamePool.CMD_OPERATION_REQUEST(false, 1, command, null);
	}

	private static String seatState(RoomConfigItem room) {
		String state = "[";
		UserGameEntity[] users = room.gameRoom.gameOverUsers;
		for (int i = 0; i < users.length; i++) {
			if (users[i].user == null) {
				state += "X,";
			} else {
				state += ActionName[users[i].lastAction] + ",";
			}
		}
		state += "]";
		return state;
	}

	static int action;
	static float chip;

	private static void testPokers() {
		// 随机发牌
		String[] pokers = new String[13 * 4];
		//初始化一副扑克
		int k = 0;
		String temp = "";
		for (int i = 0; i < TestGamePool.pokervalues.length; i++) {
			k = i * 4;
			pokers[k] = TestGamePool.pokervalues[i] + PokerColor.CLUB.value();
			pokers[k + 1] = TestGamePool.pokervalues[i] + PokerColor.DIAMOND.value();
			pokers[k + 2] = TestGamePool.pokervalues[i] + PokerColor.HEART.value();
			pokers[k + 3] = TestGamePool.pokervalues[i] + PokerColor.SPADE.value();
		}
		System.out.println("=======pokers=========");
		for (int i = 0; i < pokers.length; i++) {
			temp += pokers[i] + ",";
		}
		System.out.println(temp);
		int[] publicAndSeatPokerIndex = new int[5 + 18];
//		int[] publicPokerIndex = new int[5];
//		int[] randomPokerIndex = new int[13*4];
		int randomIndex = -1;
		int fn;
		/*System.out.println("=======publicPokerIndex=========");
		for (int i = 0; i < publicPokerIndex.length; i++) {
			fn = 0;
			while (true) {
				randomIndex = RandomUtil.next(pokers.length);
				fn++;
				if (!CalculateCard.contains(publicPokerIndex, randomIndex, 0, i))
					break;
			}
			publicPokerIndex[i] = randomIndex;
			System.out.println(fn);
		}
		temp = "";
		for (int i = 0; i < publicPokerIndex.length; i++) {
			temp += publicPokerIndex[i] + ",";
		}
		System.out.println(temp);*/
		System.out.println("=======publicAndSeatPokerIndex=========");
		temp = "";
		for (int i = 0; i < publicAndSeatPokerIndex.length; i++) {
			fn = 0;
			while (true) {
				randomIndex = RandomUtil.next(pokers.length);
				fn++;
				if (!CalculateCard.contains(publicAndSeatPokerIndex, randomIndex, 0, i))
					break;
			}
			publicAndSeatPokerIndex[i] = randomIndex;
			System.out.println(fn);
			temp += publicAndSeatPokerIndex[i] + ",";
		}
		System.out.println(temp);
		System.out.println("=======发牌结果=========");
		temp = "公共牌:";
		for (int i = 0; i < 5; i++) {
			temp += pokers[publicAndSeatPokerIndex[i]] + ",";
		}
		temp += "9个坐位的牌:";
		//5(5+9)~
		for (int i = 1; i <= 9; i++) {
			temp += "坐位1:" + pokers[publicAndSeatPokerIndex[i + 4]] + ",";
			temp += pokers[publicAndSeatPokerIndex[i + 4 + 9]] + ",";
		}
		System.out.println(temp);
		System.out.println("=======替换牌，随机取非当前的牌=========");
		temp = "";
		fn = 0;
		while (true) {
			randomIndex = RandomUtil.next(pokers.length);
			fn++;
			if (!CalculateCard.contains(publicAndSeatPokerIndex, randomIndex))
				break;
		}
		System.out.println(fn + " 得到 " + randomIndex);
		/*System.out.println("=======randomPokerIndex=========");
		temp = "";
		for (int i = 0; i < randomPokerIndex.length; i++) {
			fn = 0;
			while (true) {
				randomIndex = RandomUtil.next(pokers.length);
				fn++;
				if (!CalculateCard.contains(randomPokerIndex, randomIndex, 0, i))
					break;
			}
			randomPokerIndex[i] = randomIndex;
			System.out.println(fn);
			temp += randomPokerIndex[i] + ",";
		}
		System.out.println(temp);*/
	}

//	private static void testWinner() {
//		CalculateWinner();
//	}

	public static List<UserInfoEntity> userSeats = new ArrayList<UserInfoEntity>();// 玩家坐位数组,升序[4,8]
	public static String[] PublicCard = new String[] { "Kc", "5h", "4c", "7s", "7c" };

	/*public static void CalculateWinner() {
		UserInfoEntity user;
		for (int i = 1; i <= 9; i++) {
			user = new UserInfoEntity();
			user.card1 = i + "h";
			user.card2 = i + "c";
			userSeats.add(user);
			bonusPools[i - 1] = 900;
		}
		// 计算牌型,所有玩家中，最大的手牌
		Iterator<UserInfoEntity> it = userSeats.iterator();

		while (it.hasNext()) {
			user = it.next();
			user.setMaxHandcard(TestGamePool.countCardType(PublicCard, new String[] { user.card1, user.card2 }));
		}

		// 计算每个边池的赢家, 分配边池
		// 计算获胜边池玩家
		// 得到所有玩家中，最大的手牌
		ArrayList<UserInfoEntity> sortWinner = new ArrayList<UserInfoEntity>();
		ArrayList<UserInfoEntity> winner = new ArrayList<UserInfoEntity>();
		sortWinner.addAll(userSeats);
		Collections.sort(sortWinner);
		System.out.println("排序后为:");
		for (int i = 0; i < sortWinner.size(); i++) {
			System.out.println(sortWinner.get(i).getMaxHandcard().toString());
		}
		int result;
		winner.add(sortWinner.get(0));
		UserInfoEntity nextUser;
		int winCount;
		for (int i = 0; i < sortWinner.size(); i++) {
			user = sortWinner.get(i);
			if (i >= sortWinner.size() - 1) {
				break;
			} else {
				nextUser = sortWinner.get(i + 1);
			}
			System.out.println("排序 前type:" + user.cardType() + " 后type:" + nextUser.cardType());
			if (user.cardType() > nextUser.cardType()) {
				winner.add(user);
				break;
			} else {
				result = user.isMoreThan(nextUser);
				if (result == 0) {
					winner.add(nextUser);
					i++;
				} else {
					// winner.add(user);
					break;
				}
			}

		}
		winCount = winner.size();

	}*/

	static String[] arrCardType = new String[] { "高牌", "一对", "两对", "三条", "顺子", "同花", "葫芦", "四条", "同花顺", "皇家同花顺" };
	static GameRoomEntity testgame = new GameRoomEntity();

	private static void testCardType() {
		String[] arrCards = new String[] { "1h", "2h", "3h", "4h", "5h" };
		testgame.gameOverUsers[0].cards[0] = "7s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 8);
		arrCards = new String[] { "Jd", "7s", "5h", "2d", "6s" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "Th";
		showCardTip(arrCards, 0);
		arrCards = new String[] { "8c", "8h", "7s", "Jd", "4h" };// type,葫芦?
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "Th";
		showCardTip(arrCards, 1);
		arrCards = new String[] { "Ts", "Th", "2d", "2c", "7s" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 2);
		arrCards = new String[] { "8d", "8c", "8h", "Js", "Ts" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 3);
		arrCards = new String[] { "4d", "5c", "6h", "7s", "8s" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 4);
		arrCards = new String[] { "3h", "7h", "Th", "5h", "Kh" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 5);
		arrCards = new String[] { "8d", "8c", "8h", "Jc", "Jh" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 6);
		arrCards = new String[] { "6d", "6c", "6h", "6s", "4d" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 7);
		arrCards = new String[] { "Ks", "Qs", "Js", "Ts", "9s" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 8);
		arrCards = new String[] { "As", "Ks", "Qs", "Js", "Ts" };
		testgame.gameOverUsers[0].cards[0] = "9s";
		testgame.gameOverUsers[0].cards[1] = "7h";
		showCardTip(arrCards, 9);
	}

	private static void testCardType1() {
		String[] arrCards = new String[] { "3d", "As", "6h", "Jh", "8d" };
		testgame.gameOverUsers[0].cards[0] = "3h";
		testgame.gameOverUsers[0].cards[1] = "3c";
		showCardTip(arrCards, 3);
	}

	private static void showCardTip(String[] arrCards, int type) {
		testgame.PublicCard = arrCards;
		String allcards = "";
		for (int i = 0; i < testgame.PublicCard.length; i++) {
			allcards += testgame.PublicCard[i] + ",";
		}
		allcards += testgame.gameOverUsers[0].cards[0] + ",";
		allcards += testgame.gameOverUsers[0].cards[1] + ",";
		System.out.println(allcards + "下面的类型应该是：" + arrCardType[type]);
		testgame.gameOverUsers[0].calculateCard();
		WinCardEntity cardType = testgame.gameOverUsers[0].getMaxHandcard();
		System.out.println("type," + arrCardType[cardType.getType()] + cardType.toString());
		return;
	}

	static int[] bonusPools = new int[9];
	static int curBonus = 0;
	static int[][] bonusSeats = new int[9][9];
	static Map<Integer, ArrayList<Integer>> seatBonusMap = new HashMap<Integer, ArrayList<Integer>>();

	private static void testInBonus() {
		// int[] seatChip = new int[] { 3, 2, 1, 4, 5, 6, 7, 8, 8 };
		for (int i = 0; i < 9; i++) {
			seatBonusMap.put(i, new ArrayList<Integer>());
		}
		int[] seatChip = new int[] { 100, 0, 0, 0, 0, 0, 0, 300, 200 };
		inBonusPool(seatChip);
		seatChip = new int[] { 100, 0, 0, 0, 0, 0, 0, 100, 100 };
		inBonusPool(seatChip);
		seatChip = new int[] { 100, 0, 0, 0, 0, 0, 0, 100, 100 };
		inBonusPool(seatChip);
		seatChip = new int[] { 200, 0, 0, 0, 0, 0, 0, 100, 100 };
		inBonusPool(seatChip);

	}

	private static void putBonus(int bonusIndex, Integer seatId) {
		if (!seatBonusMap.get(bonusIndex).contains(seatId)) {
			seatBonusMap.get(bonusIndex).add(seatId);
		}
	}

	static class SeatChip implements Comparable<SeatChip> {
		int chip;
		int seatId;

		public SeatChip(int _seatId, int _chip) {
			this.seatId = _seatId;
			this.chip = _chip;
		}

		public int compareTo(SeatChip o) {
			if (o instanceof SeatChip) {
				return chip > o.chip ? 1 : -1;
			}
			return 0;
		}
	}

	private static void inBonusPool(int[] seatChip) {
		ArrayList<SeatChip> seatChipList = new ArrayList<SeatChip>();
		for (int i = 0; i < seatChip.length; i++) {
			if (seatChip[i] > 0) {
				seatChipList.add(new SeatChip(i + 1, seatChip[i]));
			}
		}
		Collections.sort(seatChipList);
		Integer chip;
		int size;
		int singleTotal = 0;
		SeatChip curSeatChip;
		while (seatChipList.size() > 0) {
			int baseChip = seatChipList.get(0).chip - singleTotal;
			singleTotal += baseChip;
			size = seatChipList.size();
			for (int i = 0; i < size; i++) {
				curSeatChip = seatChipList.get(i);
				chip = seatChipList.get(i).chip;
				chip = chip - singleTotal;
				bonusPools[curBonus] += baseChip;
				putBonus(curBonus, curSeatChip.seatId);
				// bonusSeats[curBonus][curSeatChip.seatId - 1] = 1;
				if (chip == 0) {
					seatChipList.remove(i);
					// System.out.println("移除了减为0的一项，当前长度:" +
					// seatChipList.size());
					i--;
					size--;
				}
			}
			System.out.println("第边" + (curBonus + 1) + "池形成,总额:" + bonusPools[curBonus] + " 当前桌上筹码长度:" + seatChipList.size());
			if (baseChip > 0 && seatChipList.size() > 0) {
				curBonus++;
			}

		}
		StringBuilder sb = new StringBuilder("奖池已形成:");
		ArrayList<Integer> seatBonus;
		for (int i = 1; i <= bonusPools.length; i++) {
			if (bonusPools[i - 1] <= 0) {
				break;
			}
			sb.append(i + ":" + bonusPools[i - 1] + " ;");
			sb.append("该边池下注的坐位:");
			seatBonus = seatBonusMap.get(i - 1);
			for (int j = 0; j < seatBonus.size(); j++) {
				sb.append(seatBonus.get(j) + " ");
			}
			// for (int j = 0; j < bonusSeats[i - 1].length; j++) {
			// if (bonusSeats[i - 1][j] == 1) {
			// sb.append((j + 1) + " ");
			// }
			// }
		}
		System.out.println(sb.toString());
	}

	private static void testSort() {
		List<Integer> userSeats = new ArrayList<Integer>();
		userSeats.add(3);
		userSeats.add(9);
		userSeats.add(5);
		userSeats.add(1);
		Collections.sort(userSeats);
		Iterator<Integer> it = userSeats.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}

	private static void testRoomcode() {
		int roomCount = 101;
		int floorCount = roomCount / 5;
		int roomCode;
		int num;
		for (int i = 1; i <= roomCount; i++) {
			num = (((i - 1) / floorCount) + 1);
			roomCode = num * 100 + (i - floorCount * (num - 1));
			System.out.println(i + ":" + num + ":" + roomCode);
		}
	}

	/* private static void printRoomtypeMap() { Iterator<Map.Entry<String,
	 * RoomConfigXml>> it = NetConfig.roomTypeMap.entrySet().iterator();
	 * Map.Entry<String, RoomConfigXml> room; Map.Entry<String, RoomConfigItem>
	 * item; Iterator<Map.Entry<String, RoomConfigItem>> ite; while
	 * (it.hasNext()) { room = it.next(); System.out.println("room type:" +
	 * room.getKey()); ite = room.getValue().ItemsMap.entrySet().iterator();
	 * while (ite.hasNext()) { item = ite.next();
	 * System.out.println(String.format("%s %s", item.getValue().id,
	 * item.getValue().name)); } } } */

	private static void testGetTime() {
		long test = 24 * 60 * 60 * 1000 + 60 * 60 * 1000 + 60 * 1000 + 1000 + 1;
		System.out.println(getTime(test));
	}

	private static String getTime(long spendTime) {
		int day = (int) spendTime / (24 * 60 * 60 * 1000);
		long milisecond = spendTime % (24 * 60 * 60 * 1000);
		int hour = (int) milisecond / (60 * 60 * 1000);
		milisecond = milisecond % (60 * 60 * 1000);
		int minute = (int) milisecond / (60 * 1000);
		milisecond = milisecond % (60 * 1000);
		int second = (int) milisecond / 1000;
		milisecond = milisecond % 1000;
		return String.format("%s天%s时%s分%s秒%s毫秒", day, hour, minute, second, milisecond);
	}

	private static void testDaemon() {
		Thread th1 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 10; i++) {
					System.out.println("普通线程执行:" + i);
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "thnormal");

		Thread th2 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 20; i++) {
					System.out.println("守护线程执行:" + i);
					try {
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "thDaemon");
		// th2.setDaemon(true);
		th1.start();
		th2.start();
	}

	private static void testSqlserver() {
		String dbDriver = "net.sourceforge.jtds.jdbc.Driver";
		String strConnection = "jdbc:jtds:sqlserver://localhost:1433/Db_Wandian";
		String user = "sa1";
		String password = "1234";
		Connection conn = null;
		try {
			Class.forName(dbDriver);
			conn = DriverManager.getConnection(strConnection, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private static void testAutoAdd() {
		try {
			TestDao testDao = new TestDaoImpl(new DBMgr(0));
			for (int i = 0; i < 100; i++) {
				System.out.println(testDao.ReturnAutoAddCount());
				// System.out.println(testDao.AutoAddCount());
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	private static void testPriorityBlockingQueue() {
		// ThreadPriorityScheduleDemo.testPriorityBlockingQueue();
		// ThreadPriorityScheduleDemo.testCmdPriorityBlockingQueue();
		System.out.println(DateUtil.format(new Date(23124349322762L)));
	}

	private static void testThreadPool() {
		if (TimerMgr.init(10)) {
			for (int i = 0; i < 10; i++) {
				TimerMgr.push(new Runnable() {
					public void run() {
						ThreadPool.getInstance().Push(new TimerCommand());
					}
				}, 1, 1);
			}
		}
		// 10分钟之后停止
		TimerMgr.shutdown(10, TimeUnit.MINUTES);
	}

	private static void commandConsole() throws InterruptedException, IOException {
		String mycmd;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			mycmd = br.readLine();
			if ("exit".equals(mycmd)) {
				TimerPool.stop();
				break;
			} else if ("start".equals(mycmd)) {
				testTimerPool();
			} else if ("stop".equals(mycmd)) {
				TimerPool.stop();
			} else if ("timercmd".equals(mycmd)) {
				TimerPool.printThreadPoolStatus();
			} else {
				System.out.println("command is invalide!");
			}
			Thread.sleep(1);
		}
		br.close();
		System.out.println(Log.getCurStackMsg("system exit"));
	}

	private static void testTimerPool() {

		TimerCommand command;
		if (TimerPool.start(5)) {
			for (int i = 1; i <= 10; i++) {
				command = new TimerCommand();
				command.totalCount = 2;
				command.initialDelay = 1000L;
				command.name = "command_" + i;
				// command.command = new SimpleRunnable(command.name);
				try {
					System.out.println("添加命令" + i + TimerPool.Add(command));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	static class SimpleRunnable implements Runnable {
		String name;

		public SimpleRunnable(String _name) {
			name = _name;
		}

		short count = 0;

		public void run() {
			count++;
			System.out.println(name + ":" + count);
		}
	}

	private static void testConnection() {
		System.out.println("suc");
		String mycmd;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			if (DbConnectionTest.initConnection()) {
			} else {
				System.out.println("err");
			}
			while (true) {
				try {
					mycmd = br.readLine();
					if ("exit".equals(mycmd))
						break;
					if ("testMySql".equals(mycmd))
						DbConnectionTest.testMySql();
					else if ("testInsert".equals(mycmd))
						DbConnectionTest.testInsert();
					else if ("testInsertTb1".equals(mycmd))
						DbConnectionTest.testThreads(1);
					else if ("testInsertTb2".equals(mycmd))
						DbConnectionTest.testThreads(2);
					else if ("testBatchInsertTb1".equals(mycmd))
						DbConnectionTest.testThreads(3);
					else if ("testBatchInsertTb2".equals(mycmd))
						DbConnectionTest.testThreads(4);
				} catch (Exception e) {
					e.printStackTrace();
				}

//			DbConnectionTest.executeNoQuery("sp_getUser", 0, 1);
//			DbConnectionTest.executeProcedureReturn("", 0, 1);

			}// end while
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static void testRandom() {
		Random random = new Random();
		int minDelay = 1000;
		int maxDelay = 5000;
		for (int i = 0; i < 20; i++) {
			System.out.println(RandomUtil.next(minDelay, maxDelay));
		}
	}

	private static void testScheduledExecutorService() {
		// BlockingQueueTest.testScheduledThreadPoolExecutor();
		BlockingQueueTest.testTimerMfr();
	}

	private static void testReentrantLock() {
		ReentrantLockTest test = new ReentrantLockTest();
		test.Test();
	}

	private static void testExecutor() {
		// BlockingQueueTest.testBasket();
		BlockingQueueTest.testSchedule();
	}

	private static void testDb() throws Throwable {

		if (!initComponent(Config.initConfig(GameData.CONFIGPATH), "加载配置文件")) {
			return;
		}
		// if (!initComponent(DBPoolMgr.init(Config.getValue("db.path")),
		// "初始化DB连接池")) {
		// return;
		// }
		// UserInfoDao userDao = new UserInfoDaoImpl();
		// // UserInfoEntity user = userDao.getUserInfo(1);
		// UserInfoEntity user = new UserInfoEntity();
		// user.setUserName("UserName");
		// user.setRealName("RealName");
		// user.setNickName("tNickName");
		// user.setOp((short) 1);
		// userDao.addUserInfo(user);
		// System.out.println(user.getNickName());

		// ChatrecordDao chatDao = new ChatrecordDaoImpl(new DBMgr(1));
		// //单插入
		// ChatrecordEntity chat = new ChatrecordEntity();
		// chat.setUserId(1);
		// chat.setMessage("这下插入可以啦");
		// TimeWatch timerwatch = new TimeWatch("test");
		/* for (int i = 0; i < 100; i++) { chat.setOp((short) 1);
		 * chatDao.addChatrecord(chat); }
		 * timerwatch.stop("100次插入.map,方式返回bool"); timerwatch.start(); for (int
		 * i = 0; i < 100; i++) { chat.setOp((short) 1);
		 * System.out.println(chatDao.add(chat).getId()); }
		 * timerwatch.stop("100次插入.map,方式返回entity"); timerwatch.start(); for
		 * (int i = 0; i < 100; i++) { chat.setOp((short) 1);
		 * chatDao.addChatrecord2(chat); }
		 * timerwatch.stop("100次插入.object方式返回bool");
		 * 
		 * timerwatch.start(); for (int i = 0; i < 100; i++) {
		 * chat.setOp((short) 1);
		 * System.out.println(chatDao.add2(chat).getId()); }
		 * timerwatch.stop("100次插入.object方式返回entity"); */
		// chat.setOp((short) 1);
		// chatDao.batchAdd(chat, 100);
		// timerwatch.stop("100sqlBatch方式返回bool");
		// 多插入
		// 单更新
		// 多更新
		// 单删除
		// 多删除
		// 存储过程返回table
		// 存储过程output
		// 事务，插入，查询
		// chatDao.delChatrecord(2);
		CommonDaoManager.init(1);// 启动通用数据库
		// boolean result = CommonDaoManager
		// .UserInfoDao(0)
		// .updateUserInfo(
		// "  UPDATE t_userinfo SET  CurrentState=?,LastLoginTime=?,LastLoginIp=?,IsPlaying=?,CurrentServerId=?,CurrentRoomId=?  Where UserId=? ;",
		// 1, new Timestamp(System.currentTimeMillis()),
		// "127.0.0.1", 1, 1, 1, 1);
		// `CurrentState`=?,`LastLoginTime`=?,`LastLoginIp`=?,`IsPlaying`=?,`Stake`=?,`CurrentServerId`=?,`CurrentRoomId`=?,`Money`=?

		// String
		// sql="INSERT INTO t_Exchange (ServerId ,RoomdId ,GameId   ,UserId   ,Money   ,Stake   ,LeftMoney   ,CreateTime) VALUES(?,?,?,?,?,?,?,?)";
		// boolean result = CommonDaoManager
		// .UserInfoDao(0)
		// .updateUserInfo(sql,1,2,3,1,100,100,200,new
		// Timestamp(System.currentTimeMillis()));
		// boolean result = CommonDaoManager.GameRoomDao(0).addGameLog(1, 1, new
		// UserInfoEntity(), 1, 10, 1, 1, 1, "test");
		// System.out.println(result);
		GameRoomEntity gameRoom = new GameRoomEntity();
		gameRoom.ServerId = 1;
		gameRoom.beforeAdd();
		if (CommonDaoManager.GameRoomDao(0).addBeginGameLog(gameRoom)) {
			System.out.println("插入游戏记录成功，游戏id:" + gameRoom.GameId);
		} else {
			System.out.println("插入游戏记录失败！");
		}
		// gameRoom.GameId = 1;
		// if (CommonDaoManager.GameRoomDao(0).saveGameRoom(gameRoom)) {
		// System.out.println("插入游戏记录成功，游戏id:" + gameRoom.GameId);
		// } else {
		// System.out.println("插入游戏记录失败！");
		// }
		/* List<AnnounceEntity> announces =
		 * CommonDaoManager.LobbyDao(0).getAnnouce(); Iterator<AnnounceEntity>
		 * it = announces.iterator(); while (it.hasNext()) {
		 * System.out.println(it.next().title); } */
		// List<FriendsEntity> friends =
		// CommonDaoManager.FriendsDao(0).getFriendList(4);
		// System.out.println(friends.size());
	}

	public static boolean initComponent(boolean initResult, String componentName) {
		if (!initResult)
			Log.error(componentName + "错误");
		else {
			Log.info(componentName + "加载完成");
		}
		return initResult;
	}

}
